#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI童话书启动脚本
"""

import os
import sys
import logging
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from fairy_tale_config import AppConfig
from ai_fairy_tale_book import FairyTaleApp
from web_interface import create_web_app

def setup_logging(config):
    """设置日志"""
    log_dir = Path("logs")
    log_dir.mkdir(exist_ok=True)
    
    logging.basicConfig(
        level=getattr(logging, config.logging.level),
        format=config.logging.format,
        handlers=[
            logging.FileHandler(config.logging.file_path, encoding='utf-8'),
            logging.StreamHandler(sys.stdout)
        ]
    )

def check_dependencies():
    """检查依赖"""
    required_packages = [
        'flask', 'paddlepaddle', 'paddlenlp', 'numpy', 'requests'
    ]
    
    missing_packages = []
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"❌ 缺少依赖包: {', '.join(missing_packages)}")
        print("请运行: pip install -r requirements.txt")
        return False
    
    return True

def check_model():
    """检查模型文件"""
    config = AppConfig()
    model_path = Path(config.model.model_path)
    
    if not model_path.exists():
        print(f"❌ 模型文件不存在: {model_path}")
        print("请确保ERNIE-4.5-0.3B-Paddle模型已正确下载")
        return False
    
    print(f"✅ 模型文件检查通过: {model_path}")
    return True

def main():
    """主函数"""
    print("🌟 启动AI智能童话书应用...")
    
    # 检查依赖
    if not check_dependencies():
        sys.exit(1)
    
    # 检查模型
    if not check_model():
        print("⚠️  模型文件缺失，但应用仍可启动（将使用模拟模式）")
    
    # 加载配置
    config = AppConfig()
    
    # 设置日志
    setup_logging(config)
    logger = logging.getLogger(__name__)
    
    try:
        # 初始化AI应用
        logger.info("初始化AI童话书应用...")
        fairy_tale_app = FairyTaleApp(config)
        
        # 创建Web应用
        logger.info("创建Web界面...")
        web_app = create_web_app(fairy_tale_app, config)
        
        # 启动应用
        logger.info(f"启动Web服务器 - http://{config.web.host}:{config.web.port}")
        print(f"🚀 应用已启动！")
        print(f"📱 请在浏览器中访问: http://localhost:{config.web.port}")
        print(f"🎯 按 Ctrl+C 停止应用")
        
        web_app.run(
            host=config.web.host,
            port=config.web.port,
            debug=config.web.debug
        )
        
    except KeyboardInterrupt:
        logger.info("用户中断，正在关闭应用...")
        print("\n👋 应用已关闭")
    except Exception as e:
        logger.error(f"应用启动失败: {e}")
        print(f"❌ 启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()